/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.service;

import java.io.StringReader;
import java.util.Comparator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import knowledgebase.model.DocumentBlock;

/**
 *
 * @author eugene
 */
public class DocBlockCpmparator implements Comparator<DocumentBlock> {
    
    private XMLInputFactory factory;

    public DocBlockCpmparator() {
        factory = XMLInputFactory.newInstance();
    }
    
    private Integer getBlockIndex(DocumentBlock block) {
        XMLStreamReader r = null;
        try {
            r = factory.createXMLStreamReader(new StringReader(block.getData()));
            r.nextTag();
        } catch (XMLStreamException ex) {
            Logger.getLogger(DocBlockCpmparator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return r != null ? Integer.parseInt(r.getAttributeValue(null, "index")) : null;
    }

    @Override
    public int compare(DocumentBlock o1, DocumentBlock o2) {
        return getBlockIndex(o1) - getBlockIndex(o2);
    }
}
